package main

import (
	"fmt"
	"reflect"
	"sync"
	"sync/atomic"
	"time"
)

// import "999_code_test/add"
// import "add"
// 具体待执行任务
type Task struct {
	f func() error
}

// func NewTask(funa func() error) *Task {
// 	return &Task{
// 		f: funa,
// 	}
// }

type Pool struct {
	RunningWorders int64      // 正在执行任务的 goroutine 数量
	Capacity       int64      // 协程池容量，最大 goroutine 数量
	JobCh          chan *Task // worker 获取任务管道
	sync.Mutex                // 继承互斥锁，实现加锁功能
}

// 创建任务，传入一个函数，返回一个 Task
func NewTask(funcArg func() error) *Task {
	return &Task{
		f: funcArg,
	}
}

// 创建协程池
func NewPool(capacity int, taskNum int) *Pool {
	return &Pool{
		Capacity: int64(capacity),
		JobCh:    make(chan *Task, taskNum),
	}
}
func (p *Pool) GetCap() int64 {
	return p.Capacity
}
func (p *Pool) incRunning() {
	atomic.AddInt64(&p.RunningWorders, 1)
}
func (p *Pool) decRunning() {
	atomic.AddInt64(&p.RunningWorders, -1)
}
func (p *Pool) GetRunningWorkers() int64 {
	return atomic.LoadInt64(&p.RunningWorders)
}

func (p *Pool) AddTask(task *Task) {
	p.Lock()
	defer p.Unlock()
	// 添加任务
	// 池子没满，创建 goroutine
	if p.Capacity > p.RunningWorders {
		p.Run()
	}
	// 任务添加到任务队列
	p.JobCh <- task
}
func (p *Pool) Run() {
	p.incRunning()
	go func() {
		defer func() {
			p.decRunning()
		}()
		for task := range p.JobCh {
			task.f()
		}
	}()
}

type Student struct {
	name string `json:"full name"`
	id   int	`json:"id index"`
}
type classmate Student

func main() {
	fmt.Println("abc")
	// _ = Sub(12, 9)
	// fmt.Println(add.Add(12, 13))
	pool := NewPool(5, 10)
	// var i int64
	for i := 0; i < 20; i++ {
		pool.AddTask(NewTask(func() error {
			// a := atomic.LoadInt64(&i)
			// fmt.Printf("任务id %+v\n", a)
			fmt.Println(reflect.TypeOf(i))
			return nil
		}))
	}
	time.Sleep(time.Second)
	var a int32
	a = 10
	va1 := reflect.ValueOf(a)
	fmt.Println(reflect.TypeOf(a))
	fmt.Println(va1)
	fmt.Println(va1.String())
	stu := Student{
		"abc",
		1234,
	}
	fmt.Println(reflect.TypeOf(stu))
	fmt.Printf("type of stu1, %+v\n", reflect.TypeOf(stu).String())
	fmt.Printf("kind of stu1, %+v\n", reflect.TypeOf(stu).Kind())
	va2 := reflect.ValueOf(stu)
	fmt.Println(va2)
	fmt.Println(va2.String())
	stu2 := classmate{
		"def",
		456,
	}
	fmt.Printf("type of stu2, %+v\n", reflect.TypeOf(stu2).String())
	fmt.Printf("kind of stu2, %+v\n", reflect.TypeOf(stu2).Kind())
	val_stu2 := reflect.ValueOf(stu2)
	fmt.Printf("num field %v\n", val_stu2.NumField())
	for i := 0; i < val_stu2.NumField(); i++ {
		fmt.Printf("member val %v %v\n", i, val_stu2.Field(i).Type().Name())
	}
	stu2_type := reflect.TypeOf(stu2).Elem()
	for i:=0;i<stu2_type.NumField();i++{
		field := 
	}
	m := map[int]string{
		100: "10000",
		200: "20000",
	}
	m_val := reflect.ValueOf(m)
	for _, v := range m_val.MapKeys(){
		field := m_val.MapIndex(v)
		fmt.Println(v, field)
	}

}
